package com.magic8ball;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	
	private EditTextPreference[] customTitles;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // load preferences from xml
        addPreferencesFromResource(R.xml.preferences);
        
        // preference variables
        customTitles = new EditTextPreference[21];
        int i = 1;
        while(i <= 20)
        {
        	customTitles[i] = (EditTextPreference)getPreferenceScreen().findPreference("custom"+i);
        	i++;
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
		
		// set the default titles on the custom response preferences
        int i = 1;
        while(i <= 20)
        {
        	if (preferences.getString("custom"+i, "").equals(""))
        		customTitles[i].setTitle(getResources().getString(R.string.response_title)+" "+i);
        	else
       			customTitles[i].setTitle(preferences.getString("custom"+i, getResources().getString(R.string.response_title)+" "+i));
        	i++;
        }

        // register key listener           
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // unregister key listener        
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);    
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {		
		// set the titles on the custom response preferences
        int i = 1;
        while(i <= 20)
        {
        	if (key.equals("custom"+i))
        		if (sharedPreferences.getString(key, "").equals(""))
        			customTitles[i].setTitle(getResources().getString(R.string.response_title)+" "+i);
        		else
        			customTitles[i].setTitle(sharedPreferences.getString(key, ""));
        	i++;
        }
	}
}